package portal.servlet;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import java.net.URI;
import java.net.URL;
import java.net.URLConnection;

import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.*;
import javax.servlet.http.*;

import oracle.stellent.ridc.IdcClient;

import oracle.webcenter.content.stellent.StellentUtils;
import oracle.webcenter.doclib.internal.config.DocLibADFConfigUtils;

public class ContentAttachFileServelet extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=UTF-8";
    private IdcClient idcClient;
    private String connectionName;
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        try {
            connectionName = DocLibADFConfigUtils.getPrimaryConnectionName();
            idcClient = StellentUtils.getIdcClient(connectionName);


        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void doGet(HttpServletRequest request,
                      HttpServletResponse response) throws ServletException,
                                                           IOException {
        InputStream raw =null;
        ServletOutputStream oStream  =null;
        try {
            response.setContentType(CONTENT_TYPE);
            String srurl = request.getRequestURI();
            String dID="";
            String dDocName="";
            String attachfile="";
            String strpara = "";
            String filename="";
            //String querystr =request.getQueryString() ;
            //querystr = URLDecoder.decode(querystr, "UTF-8");
            request.setCharacterEncoding("UTF-8");
            if (request.getQueryString() != null)
            {
                strpara = request.getQueryString();
                dID = request.getParameter("dID");
                dDocName = request.getParameter("dDocName");
                attachfile = request.getParameter("Rendition");
                filename = request.getParameter("filename");
            }
            //PrintWriter out = response.getWriter();
            //out.println("http://localhost:16200" + srurl);
            //srurl = srurl.substring(srurl.indexOf("cs"), srurl.length());
            String connStr = idcClient.getConfig().getConnectionString();
            String ip =
                connStr.substring(connStr.indexOf("/") + 2, connStr.length());
            ip = ip.substring(0, ip.indexOf(":"));
            String url =
                "http://" + ip + ":16200/cs/idcplg?IdcService=GET_FILE&dID=" + dID + "&dDocName=" + dDocName + "&Rendition=" + URLEncoder.encode(attachfile, "UTF-8") + "&allowInterrupt=1";
                        
            URL u =new URL(url);
            URLConnection uc = u.openConnection();
            //out.println(filename);
            String contentType = uc.getContentType();
            int contentLength = uc.getContentLength();
            raw = uc.getInputStream();
            
            response.setContentType(contentType);
            response.setHeader( "Content-Disposition", "attachment; filename=\"" + filename + "\"" );
            response.setContentLength(contentLength);
            oStream = response.getOutputStream();

            // Now, loop through buffer reads of our content, and send it to the client:
            byte[] buffer = new byte[1024];
            int len;
            while ((len = raw.read(buffer)) != -1) {
                oStream.write(buffer, 0, len);
            }

            // Now that we've sent the image data to the client, close down all the resources:
//            raw.close();
//
//            oStream.flush();
//            oStream.close();
        }

        catch (IOException ioex) {
            ioex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            if(raw!=null)
                raw.close();
            if(oStream!=null)
            {
                oStream.flush();  
                oStream.close();
            }
        }
        

    }

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
                                                            IOException {
        //doGet(request,response);
    }
}
